use crate::tui::app::{App, AppResult, NavDirection};
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseEvent, MouseEventKind};

/// Handles the key events and updates the state of [`App`].
pub async fn handle_key_events(key_event: KeyEvent, app: &mut App) -> AppResult<()> {
    match key_event {
        // Exit application on `ESC` or `q`
        KeyEvent {
            code: KeyCode::Char('q') | KeyCode::Esc,
            modifiers: KeyModifiers::NONE,
            ..
        } => app.quit().await,
        // Exit application on `Ctrl-C`
        KeyEvent {
            code: KeyCode::Char('c') | KeyCode::Char('C'),
            modifiers: KeyModifiers::CONTROL,
            ..
        } => app.quit().await,
        KeyEvent {
            code,
            modifiers: KeyModifiers::ALT,
            ..
        } if code == KeyCode::Char('1')
            || code == KeyCode::Char('2')
            || code == KeyCode::Char('3')
            || code == KeyCode::Char('4') =>
        {
            match code {
                KeyCode::Char(c) => app.switch_tab(c.to_digit(10).unwrap() as usize - 1).await,
                _ => {}
            }
        }
        KeyEvent {
            code: KeyCode::Up,
            kind: KeyEventKind::Press,
            modifiers: KeyModifiers::NONE,
            ..
        } => app.goto(NavDirection::Up(1)).await,
        KeyEvent {
            code: KeyCode::Down,
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Press,
            ..
        } => app.goto(NavDirection::Down(1)).await,
        KeyEvent {
            code: KeyCode::Left,
            modifiers: KeyModifiers::NONE,
            ..
        } => app.goto(NavDirection::Left(1)).await,
        KeyEvent {
            code: KeyCode::Right,
            modifiers: KeyModifiers::NONE,
            ..
        } => app.goto(NavDirection::Right(1)).await,
        // Other handlers you could add here.
        KeyEvent {
            code: KeyCode::Enter,
            modifiers: KeyModifiers::NONE,
            ..
        } => app.mark_download().await,
        _ => {}
    }
    Ok(())
}

pub async fn handle_mouse_events(e: MouseEvent, app: &mut App) -> AppResult<()> {
    match e.kind {
        MouseEventKind::Down(b) => {
            log::debug!("{e:?}");
        }
        _ => {}
    }
    Ok(())
}
